


#import "PostImageView.h"
#import "BackOverburden.h"

@interface PostImageView()

@property (nonatomic, strong) BackOverburden * burden;

@end

@implementation PostImageView

- (NSString*)randomIDStr
{
    if (!_randomIDStr)
    {
        _randomIDStr = [self uuidString];
    }
    return _randomIDStr;
}

//生成随机的uuid
- (NSString *)uuidString
{
    CFUUIDRef uuid_ref = CFUUIDCreate(NULL);
    CFStringRef uuid_string_ref= CFUUIDCreateString(NULL, uuid_ref);
    NSString *uuid = [NSString stringWithString:(__bridge NSString *)uuid_string_ref];
    CFRelease(uuid_ref);
    CFRelease(uuid_string_ref);
    return [uuid lowercaseString];
}

//网络传图到服务器
- (void)saveWithImage:(UIImage *)image withImageName:(NSString*)imageName withURL:(NSString*)urlStr withType:(NSString*)type success:(ReturnJSONBlock)dataBlock failure:(ReturnJSONFailBlock)errBlock
{
    BOOL success;
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *imageFilePath = nil;
    NSMutableData *dataM = [NSMutableData data];
    //把图片转化成数据格式
    NSData *imageData = nil;
    NSString *topStr = nil;
    if ([type isEqualToString:@"0"])
    {
        imageFilePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.jpg",imageName]];
        success = [fileManager fileExistsAtPath:imageFilePath];
        if(success)
        {
            success = [fileManager removeItemAtPath:imageFilePath error:&error];
        }
        CGSize size = image.size;
        UIImage *smallImage = [self imageByScalingAndCroppingForSize:CGSizeMake(size.width/2, size.height/2) withSourceImage:image];
        [UIImageJPEGRepresentation(smallImage, 0.7f) writeToFile:imageFilePath atomically:YES];//写入文件
        UIImage* selfPhoto = [UIImage imageWithContentsOfFile:imageFilePath];//读取图片文件
        imageData = UIImageJPEGRepresentation(selfPhoto,1.0f);
        topStr = [self topStringWithMimeType:@"application/octet-stream; charset=UTF-8" uploadFile:[NSString stringWithFormat:@"%@.jpg",imageName]];
    }
    else
    {
        imageFilePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png",imageName]];
        success = [fileManager fileExistsAtPath:imageFilePath];
        if(success)
        {
            success = [fileManager removeItemAtPath:imageFilePath error:&error];
        }
        [UIImagePNGRepresentation(image) writeToFile:imageFilePath atomically:YES];//写入文件
        UIImage* selfPhoto = [UIImage imageWithContentsOfFile:imageFilePath];//读取图片文件
        imageData = UIImagePNGRepresentation(selfPhoto);
        topStr = [self topStringWithMimeType:@"application/octet-stream; charset=UTF-8" uploadFile:[NSString stringWithFormat:@"%@.png",imageName]];
    }
    NSURL * URL = [NSURL URLWithString:urlStr];
    NSString *bottomStr1 = [self bottomStringWithName:@"pictureType" withStr:self.pictureType];
    NSString *bottomStr2 = [self bottomStringWithName:@"customerId" withStr:self.customerId];
    NSString *bottomStr3 = [self bottomStringWithName:@"companyCode" withStr:self.companyCode];
    NSString *bottomStr4 = [self bottomStringWithName:@"transType" withStr:self.transType];
    NSString *bottomStr5 = [self bottomStringWithName:@"fileSuffix" withStr:self.fileSuffix];
    [dataM appendData:[bottomStr1 dataUsingEncoding:NSUTF8StringEncoding]];
    [dataM appendData:[bottomStr2 dataUsingEncoding:NSUTF8StringEncoding]];
    [dataM appendData:[bottomStr3 dataUsingEncoding:NSUTF8StringEncoding]];
    [dataM appendData:[bottomStr4 dataUsingEncoding:NSUTF8StringEncoding]];
    [dataM appendData:[bottomStr5 dataUsingEncoding:NSUTF8StringEncoding]];
    [dataM appendData:[topStr dataUsingEncoding:NSUTF8StringEncoding]];
    [dataM appendData:imageData];
    [dataM appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    NSString * s = [NSString stringWithFormat:@"%@%@%@\r\n",boundaryStr, self.randomIDStr, boundaryStr];
    [dataM appendData:[s dataUsingEncoding:NSUTF8StringEncoding]];
    NSLog(@"topStr ＝ %@",topStr);
    NSLog(@"imageData = %@..........",imageData);
    NSLog(@"\r\n%@",s);
    // 1. Request
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL cachePolicy:0 timeoutInterval:10.0f];
    request.HTTPBody = dataM;
    request.HTTPMethod = @"POST";
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"gzip" forHTTPHeaderField:@"Content-Encoding"];
    NSString *strLength = [NSString stringWithFormat:@"%ld", (long)dataM.length];
    [request setValue:strLength forHTTPHeaderField:@"Content-Length"];
    NSString *strContentType = [NSString stringWithFormat:@"multipart/form-data;boundary=%@", self.randomIDStr];
    [request setValue:strContentType forHTTPHeaderField:@"Content-Type"];
    XYCustomStatusBar* statusBar = [[XYCustomStatusBar alloc]init];
    [statusBar showStatusMessage:@"正在上传，稍后..."];
    self.burden = [[BackOverburden alloc]init];
    [self.burden showView];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    [NSURLConnection sendAsynchronousRequest:request
     
                                       queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse
                                                                                                 
                                                                                                 *response, NSData *data, NSError *connectionError) {
                                           if (data)
                                           {
                                               NSLog(@"返回来的data = %@",data);
                                               //回传数据
                                                dataBlock(data);
                                               dispatch_async(dispatch_get_main_queue(), ^{
                                                   [self.burden removeView];
                                               });
                                               
                                           }
                                           else
                                           {
                                               NSLog(@"返回来的data = %@",data);
                                               NSLog(@"返回来的错误信息 = %@",connectionError);
                                               if (connectionError)
                                               {
                                                   //回传错误信息
                                                   errBlock(connectionError);
                                               }
                                               dispatch_async(dispatch_get_main_queue(), ^{
                                                   [statusBar showStatusMessage:@"上传图片失败！"];
                                                   [self.burden removeView];
                                                   [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
                                               });
                                           }
                                       }];
}


/**
 * 图片压缩到指定大小
 * @param targetSize 目标图片的大小
 * @param sourceImage 源图片
 * @return 目标图片
 */
- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize withSourceImage:(UIImage *)sourceImage
{
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth= width * scaleFactor;
        scaledHeight = height * scaleFactor;
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else if (widthFactor < heightFactor)
        {
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width= scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    [sourceImage drawInRect:thumbnailRect];
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil)
    NSLog(@"could not scale image");
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}

//表字段头部字符串
-(NSString *)topStringWithMimeType:(NSString *)mimeType uploadFile:(NSString *)uploadFile
{
    NSMutableString *strM = [NSMutableString string];
    [strM appendFormat:@"%@%@\r\n", boundaryStr, self.randomIDStr];
    [strM appendFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", uploadID, uploadFile];
    [strM appendFormat:@"Content-Type: %@\r\n", mimeType];
    [strM appendFormat:@"\r\n"];
    NSLog(@"表字段头部字符串 = %@", strM);
    return [strM copy];
}
//表字段尾部字符串
-(NSString *)bottomString
{
    NSMutableString *strM = [NSMutableString string];
    [strM appendFormat:@"%@%@\r\n", boundaryStr, self.randomIDStr];
    [strM appendString:@"Content-Disposition:form-data; name=\"number\"\r\n"];
    [strM appendFormat:@"\r\n"];
    [strM appendString:@"number"];//上传的参数parameter
    [strM appendFormat:@"\r\n"];
    NSLog(@"表字段尾部字符串 = %@", strM);
    return [strM copy];
}

-(NSString *)bottomStringWithName:(NSString*)name withStr:(NSString*)str
{
    NSMutableString *strM = [NSMutableString string];
    [strM appendFormat:@"%@%@\r\n", boundaryStr, self.randomIDStr];
    [strM appendString:[NSString stringWithFormat:@"Content-Disposition:form-data; name=\"%@\"\r\n",name]];
    [strM appendFormat:@"Content-Type: application/octet-stream; charset=UTF-8\r\n"];
    [strM appendFormat:@"\r\n"];
    if (str)
    {
        [strM appendString:str];//上传的参数parameter
    }
    [strM appendFormat:@"\r\n"];
    NSLog(@"%@", strM);
    return [strM copy];
}


@end
